import * as objectPath from 'object-path';
import { errorMsg } from '../locales/zh-cn';
import ErrorCode from '../constants/ErrorCode';


const data = {
  errorMsg
};

/**
 * 注册错误信息数据
 * @param userErrorMsg 错误信息
 */
export function setErrMsg(userErrorMsg) {
  data.errorMsg = {
    ...errorMsg,
    ...userErrorMsg
  };
}

/**
 * 获取错误信息`
 * @author 田尘殇Sean(sean.snow@live.com)
 * @date 16/9/9
 */
export default (payload, prefix?: string): string => {
  const {errorMsg} = data;
  const {status, message} = payload;
  if (status === ErrorCode.CUSTOM_ERROR) {
    return message;
  }
  const path = prefix ? `${prefix}.${status}` : status;
  console.log(path);
  let result = objectPath.get(errorMsg, path) || errorMsg[status] || errorMsg.UNKNOWN;
  if (typeof result === 'function') {
    return result(message);
  }
  return result;
};
